package com.mo.xi.ge.info.help

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.database.Cursor
import android.os.Build
import java.io.IOException

/**
 * date:2024/1/24
 **/

internal fun Context.versionCode(pkgName: String = this.packageName): Long {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        getAppPackageInfo(pkgName)?.longVersionCode ?: -1
    } else {
        getAppPackageInfo(pkgName)?.versionCode?.toLong() ?: -1
    }
}

internal fun PackageInfo.versionCode(): Long {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        longVersionCode
    } else {
        versionCode.toLong()
    }
}


internal fun Context.versionName(pkgName: String = this.packageName): String? {
    return getAppPackageInfo(pkgName)?.versionName
}

private fun Context.getAppPackageInfo(pkgName: String): PackageInfo? {
    try {
        val pm = packageManager
        return pm.getPackageInfo(pkgName, PackageManager.GET_SIGNATURES)
    } catch (e: Exception) {
    }
    return null
}

internal fun getInstallAllApp(context: Context): List<PackageInfo> {
    val list = context.packageManager.getInstalledPackages(
        PackageManager.GET_UNINSTALLED_PACKAGES
    )
    var i = list.size - 1
    while (i > 0) {
        if (null == context.packageManager.getLaunchIntentForPackage(list[i].packageName)) {
            list.removeAt(i)
        }
        i--
    }
    return list
}


internal fun close(cursor: Cursor?): Boolean {
    try {
        cursor?.close()
        return true
    } catch (e: IOException) {
    }
    return false
}

fun Boolean.toIntValue(): Int {
    return if (this) 1 else 0
}

